package com.server;

import com.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * @author Zxeao~Lenovo
 * @description 创建房间函数，传入要创建房间的账号
 * @return 创建成功返回true，否则为false
 * @throw 若碰到错误，会向外抛出
 */
public class CreateRoom {

    private final String account;

    public CreateRoom(String account) {
        this.account = account;
    }

    public Server createRoom() throws Exception{
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        //连接数据库
        Connection conn = DriverManager.getConnection(Config.JDBCURL, "zxeao", "123456");
        System.out.println("创建房间：数据库连接成功");

        //获取当前IP
        InetAddress iPV4 = Inet4Address.getLocalHost();
        String iP = iPV4.toString().split("/")[1];
        System.out.println("创建房间：主机ip为"+iP);

        //通过连接对象 获得Statement 对象
        String sql = String.format("SELECT account FROM `account` WHERE account='%s'", account);
        PreparedStatement statement  = conn.prepareStatement(sql);

        //执行SQL
        ResultSet res = statement.executeQuery();

        if (res.next()){
            String sql1 = String.format("UPDATE `account` SET ip = '%s' WHERE account = '%s' ", iP, account);
            PreparedStatement statement1  = conn.prepareStatement(sql1);
            int res1 = statement1.executeUpdate();
            System.out.println("创建房间：主机设备ip上传成功"+iP);
            //结束工作
            res.close();
            statement1.close();
            statement.close();
            conn.close();
            return new Server(account,iP);
        }else {
            System.out.println("创建房间失败");
            return null;
        }
    }
}
